<!DOCTYPE html>
<html lang="zh">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>draggable demo</title>
</head>

<style>
  .container {
    width: 200px;
    height: 200px;
    margin: 50px 0;
    border: 1px solid #ccc;
    border-radius: 4px;
    overflow: hidden;
    box-sizing: border-box;
    /* padding: 10px; */
    position: relative;
  }
</style>

<body>
  <div class="container"></div>

  <p draggable="true" class="text">我是一段可拖拽的文本</p>

  <script type="module">
    const container = document.querySelector(".container");
    const text = document.querySelector(".text");

    // 开始拖拽
    text.addEventListener("dragstart", (e) => {
      console.log("dragStart: ", e);

      // 设置要传输的数据
      e.dataTransfer.setData('data', "拖拽数据");

      // 设置拖动元素的样式
      const img = document.createElement("img");
      img.src = "./test.png";
      img.setAttribute("style", "width: 40px; height: 40px;");
      e.dataTransfer.setDragImage(img, 0, 0);
    });

    // 被别的拖拽进入
    container.addEventListener("dragenter", (e) => {
      e.target.style.border = "6px dashed #ccc";
      console.log("dragenter", e);
    });

    // 当拖动的元素位于目标元素之上时持续触发
    container.addEventListener("dragover", (e) => {
      // console.log("dragOver: ", e);

      // 阻止默认行为
      e.preventDefault();
    });

    // 元素离开拖放目标范围
    container.addEventListener("dragleave", (e) => {
      e.target.style.border = '';
      console.log("dragleave", e);
    });

    // 被拖动放置后调用
    container.addEventListener('drop', (e) => {
      console.log("drop: ", e);

      // 阻止默认行为
      e.preventDefault();

      // 获取拖拽数据
      const data = e.dataTransfer.getData('data');
      if (data) {
        console.log("data: ", data);
      }


      // 获取拖放的文件列表
      const files = event.dataTransfer.files;

      for (let i = 0; i < files.length; i++) {
        const file = files[i];
        console.log(`file${i + 1}`, file);
      }
    });

  </script>
</body>

</html>